#!/usr/bin/python

# Copyright (c) 2009, Purdue University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# Neither the name of the Purdue University nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Lists all hosts in a given view in the /etc/hosts format."""


__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'

from binascii import hexlify
import bisect
import socket
import struct
import sys

from roster_user_tools import cli_common_lib
from roster_user_tools import roster_client_lib
from roster_user_tools.action_flags import List
from roster_user_tools.data_flags import HostFile


class Args(List, HostFile):
  pass


def Main(args):
  """Collects command line arguments.

  Inputs:
    args: list of arguments from the command line
  """
  command = 'list'
  if( args and not args[0].startswith('-') ):
    command = args.pop(0)
  usage = ('\n'
           '\n'
           'To print out a hostfile for all records in a specific view:\n'
           '\t%s -v <view-name> -d <base-domain>'
           '\n' % tuple(sys.argv[0] for x in range(1)))
  args_instance = Args(command, ['list'], args, usage)
  options = args_instance.options

  try:
    cli_common_lib_instance = cli_common_lib.CliCommonLib(options)
  except cli_common_lib.ArgumentError, error:
    print 'ERROR: %s' % error
    sys.exit(1)

  if( not options.no_header ):
    print_list = [['target', 'assignment_host']]

  view_deps = None

  if( options.view_name == 'any' ):
    view_deps = [u'any']
  else:
    view_deps = roster_client_lib.RunFunction(
        u'ListViewAssignments', options.username,
        credfile=options.credfile, credstring=options.credstring,
        server_name=options.server,
        kwargs={'view_superset': options.view_name})['core_return']
    if( options.view_name not in view_deps ):
      print '%s is an invalid view name.' % options.view_name
      exit(1)
    view_deps = view_deps[options.view_name]

  hinfo_records = []
  a_records = []
  cnames = []
  zone_origins = {}

  for view in view_deps:
    hinfo_records.extend(roster_client_lib.RunFunction(
        u'ListRecords', options.username,
        credfile=options.credfile, credstring=options.credstring,
        server_name=options.server, kwargs={'record_type': u'hinfo',
                                            'view_name': view})['core_return'])

    a_records.extend(roster_client_lib.RunFunction(
        u'ListRecords', options.username,
        credfile=options.credfile, credstring=options.credstring,
        server_name=options.server, kwargs={'record_type': u'aaaa',
                                            'view_name': view})['core_return'])

    a_records.extend(roster_client_lib.RunFunction(
        u'ListRecords', options.username,
        credfile=options.credfile, credstring=options.credstring,
        server_name=options.server, kwargs={'record_type': u'a',
                                            'view_name': view})['core_return'])

    cnames.extend(roster_client_lib.RunFunction(
        u'ListRecords', options.username,
        credfile=options.credfile, credstring=options.credstring,
        server_name=options.server, kwargs={'record_type': u'cname',
                                            'view_name': view})['core_return'])

    zones = roster_client_lib.RunFunction(
        u'ListZones', options.username,
        credfile=options.credfile, credstring=options.credstring,
        server_name=options.server, kwargs={'view_name': view})['core_return']
    for zone in zones:
      for view in zones[zone]:
        if( zone not in zone_origins ):
          zone_origins[zone] = {}
        zone_origins[zone][view] = zones[zone][view]['zone_origin']
    del zones

  host_cnames = {}
  for record in cnames:
    if( record['assignment_host'] not in host_cnames ):
      host_cnames[record['assignment_host']] = []
    host_cnames[record['assignment_host']].append('%s.%s' % ( record['target'], 
        zone_origins[record['zone_name']][record['view_name']]))

  host_records = {}
  lookup_host_records = {}
  for record in a_records:
    try:
      dec_ip = struct.unpack("!I", socket.inet_pton(socket.AF_INET, record['assignment_ip']))[0]
    except socket.error:
      dec_ip = int(hexlify(socket.inet_pton(socket.AF_INET6, record['assignment_ip'])), 16)
    if dec_ip in host_records:
      host_records[dec_ip]['fqdn_names'].append('%s.%s' % (record['target'], zone_origins[record['zone_name']][record['view_name']]))
    else:
      host_records[dec_ip] = {'zone_origin': zone_origins[record['zone_name']][record['view_name']], 'ip': record['assignment_ip'], 'hinfo': '',
                                               'fqdn_names': ['%s.%s' % (record['target'], zone_origins[record['zone_name']][record['view_name']])]}

    lookup_host_records['%s.%s' % (record['target'], zone_origins[record['zone_name']][record['view_name']])] = dec_ip
  del a_records

  for dec_ip in host_records:
    host_records[dec_ip]['fqdn_names'].sort()

  count = 0
  host_cname_keys = host_cnames.keys()
  host_record_keys = host_records.keys()
  host_record_keys.sort()
  lookup_host_record_keys = lookup_host_records.keys()
  lookup_host_record_keys.sort()

  cnames_left = len(host_cname_keys)
  while(host_cname_keys):
    found_index = bisect.bisect(lookup_host_record_keys, host_cname_keys[count])
    if found_index > len(lookup_host_record_keys):
      continue
    else:
      host_target = lookup_host_record_keys[found_index -1]
      dec_ip = lookup_host_records[host_target]
      current_cnames = host_cnames[host_cname_keys[count]]
      host_dict =  host_records[dec_ip]
      host_dict['fqdn_names'].extend(current_cnames)

      for current_cname in current_cnames:
        lookup_host_records[current_cname] = lookup_host_records[host_target]
        bisect.insort(lookup_host_record_keys, current_cname)

      del host_cname_keys[count]
      count -= 1

    count += 1
    if count >= (cnames_left - 1):
      count = 0
      cname_count = len(host_cname_keys)
      if cname_count == cnames_left:
        break

  for record in hinfo_records:
    found_index = bisect.bisect(lookup_host_record_keys, '%s.%s' % (record['target'], zone_origins[record['zone_name']][record['view_name']]))
    if found_index > len(lookup_host_record_keys):
      continue

    host_target = lookup_host_record_keys[found_index -1]
    dec_ip = lookup_host_records[host_target]
    host_dict =  host_records[dec_ip]
    host_dict['hinfo'] = '%s %s' % (record['hardware'], record['os'])

  print '127.1\tlocalhost loghost'
  for dec_ip in host_record_keys:
    fqdns = []
    for fqdn in host_records[dec_ip]['fqdn_names']:
      if fqdn.endswith('%s.' % options.base_domain):
        if fqdn.startswith('@'):
         fqdn = fqdn[2:]
        fqdns.append(fqdn.rstrip('.'))
        fqdns.append(fqdn.split('.%s' % options.base_domain)[0])
      else:
        continue

    hinfo = ''
    if host_records[dec_ip]['hinfo']:
      hinfo = ' # %s' % host_records[dec_ip]['hinfo']
    if fqdns and not host_records[dec_ip]['ip'] == '127.0.0.1':
      print '%s\t%s%s' % (host_records[dec_ip]['ip'], ' '.join(fqdns), hinfo)

if __name__ == "__main__":
  Main(sys.argv[1:])
